#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
代理配置助手
用于快速配置、测试和管理代理列表
"""

import os
import sys
import argparse
from pathlib import Path

# 添加项目路径
cpath_current = os.path.dirname(os.path.dirname(__file__))
cpath = os.path.abspath(os.path.join(cpath_current, os.pardir))
sys.path.append(cpath)

# 代理配置文件路径
PROXY_FILE = os.path.join(cpath_current, 'instock', 'config', 'proxy.txt')
# Docker环境下的代理文件路径
DOCKER_PROXY_FILE = '/data/instockproxy.txt'


def read_proxies(file_path):
    """读取代理列表"""
    if not os.path.exists(file_path):
        return []
    
    proxies = []
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#'):
                    proxies.append(line)
        return proxies
    except Exception as e:
        print(f"读取代理文件失败: {e}")
        return []


def write_proxies(file_path, proxies, append=False):
    """写入代理列表"""
    try:
        mode = 'a' if append else 'w'
        with open(file_path, mode, encoding='utf-8') as f:
            for proxy in proxies:
                f.write(f"{proxy}\n")
        return True
    except Exception as e:
        print(f"写入代理文件失败: {e}")
        return False


def list_proxies():
    """列出当前配置的代理"""
    proxies = read_proxies(PROXY_FILE)
    
    print(f"\n{'='*60}")
    print(f"代理配置文件: {PROXY_FILE}")
    print(f"{'='*60}")
    
    if not proxies:
        print("当前没有配置任何代理")
        return
    
    print(f"\n当前配置了 {len(proxies)} 个代理:\n")
    for i, proxy in enumerate(proxies, 1):
        # 隐藏密码（如果有认证）
        if '@' in proxy:
            display_proxy = proxy.split('@')[0].split(':')[0] + ':****@' + '@'.join(proxy.split('@')[1:])
        else:
            display_proxy = proxy
        print(f"  {i:3d}. {display_proxy}")
    print()


def add_proxy(proxy):
    """添加单个代理"""
    proxies = read_proxies(PROXY_FILE)
    
    if proxy in proxies:
        print(f"代理 {proxy} 已存在，跳过")
        return
    
    if write_proxies(PROXY_FILE, [proxy], append=True):
        print(f"✓ 成功添加代理: {proxy}")
    else:
        print(f"✗ 添加代理失败: {proxy}")


def add_proxies_from_file(file_path):
    """从文件批量添加代理"""
    if not os.path.exists(file_path):
        print(f"文件不存在: {file_path}")
        return
    
    new_proxies = read_proxies(file_path)
    existing_proxies = read_proxies(PROXY_FILE)
    
    # 去重
    added_count = 0
    for proxy in new_proxies:
        if proxy not in existing_proxies:
            if write_proxies(PROXY_FILE, [proxy], append=True):
                added_count += 1
    
    print(f"✓ 成功添加 {added_count} 个新代理")
    print(f"  (跳过了 {len(new_proxies) - added_count} 个已存在的代理)")


def clear_proxies():
    """清空所有代理"""
    confirm = input("确定要清空所有代理吗？(y/N): ")
    if confirm.lower() == 'y':
        if write_proxies(PROXY_FILE, [], append=False):
            print("✓ 已清空所有代理")
        else:
            print("✗ 清空代理失败")
    else:
        print("取消操作")


def remove_proxy(proxy):
    """删除指定代理"""
    proxies = read_proxies(PROXY_FILE)
    
    if proxy not in proxies:
        print(f"代理 {proxy} 不存在")
        return
    
    proxies.remove(proxy)
    if write_proxies(PROXY_FILE, proxies, append=False):
        print(f"✓ 成功删除代理: {proxy}")
    else:
        print(f"✗ 删除代理失败")


def test_proxy(proxy):
    """测试单个代理"""
    import requests
    
    print(f"\n正在测试代理: {proxy}")
    
    # 格式化代理URL
    if not proxy.startswith('http://') and not proxy.startswith('https://'):
        proxy_url = f"http://{proxy}"
    else:
        proxy_url = proxy
    
    proxies = {
        "http": proxy_url,
        "https": proxy_url
    }
    
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.9',
    }
    
    # 测试访问东财
    test_url = "http://82.push2.eastmoney.com/api/qt/clist/get"
    params = {"pn": 1, "pz": 10}
    
    try:
        r = requests.get(
            test_url,
            proxies=proxies,
            params=params,
            headers=headers,
            timeout=10,
            verify=False
        )
        
        if r.status_code == 200:
            print(f"✓ 代理可用！状态码: {r.status_code}")
            return True
        else:
            print(f"✗ 代理不可用，状态码: {r.status_code}")
            return False
    except requests.exceptions.Timeout:
        print("✗ 代理超时")
        return False
    except requests.exceptions.ProxyError as e:
        print(f"✗ 代理错误: {str(e)[:100]}")
        return False
    except Exception as e:
        print(f"✗ 测试失败: {str(e)[:100]}")
        return False


def test_all_proxies():
    """测试所有配置的代理"""
    proxies = read_proxies(PROXY_FILE)
    
    if not proxies:
        print("当前没有配置任何代理")
        return
    
    print(f"\n开始测试 {len(proxies)} 个代理...\n")
    
    valid_proxies = []
    invalid_proxies = []
    
    for proxy in proxies:
        if test_proxy(proxy):
            valid_proxies.append(proxy)
        else:
            invalid_proxies.append(proxy)
    
    print(f"\n{'='*60}")
    print(f"测试完成！")
    print(f"总代理数: {len(proxies)}")
    print(f"可用代理: {len(valid_proxies)}")
    print(f"不可用代理: {len(invalid_proxies)}")
    print(f"{'='*60}\n")
    
    if invalid_proxies:
        print("不可用的代理列表:")
        for proxy in invalid_proxies:
            print(f"  - {proxy}")
        print()


def show_help():
    """显示帮助信息"""
    print("""
代理配置助手 - 使用说明

配置文件位置:
  - 开发环境: instock/config/proxy.txt
  - Docker环境: /data/instockproxy.txt

可用命令:
  list              - 列出当前配置的所有代理
  add <proxy>       - 添加单个代理（格式: IP:PORT 或 user:pass@IP:PORT）
  add-file <file>   - 从文件批量添加代理
  remove <proxy>    - 删除指定代理
  clear             - 清空所有代理
  test <proxy>      - 测试单个代理是否可用
  test-all          - 测试所有配置的代理
  help              - 显示此帮助信息

示例:
  python dev/代理配置助手.py list
  python dev/代理配置助手.py add 112.15.190.108:10086
  python dev/代理配置助手.py add-file dev/可用代理列表.txt
  python dev/代理配置助手.py test 112.15.190.108:10086
  python dev/代理配置助手.py test-all
  python dev/代理配置助手.py remove 112.15.190.108:10086
  python dev/代理配置助手.py clear
""")


def main():
    parser = argparse.ArgumentParser(description='代理配置助手')
    parser.add_argument('command', nargs='?', help='命令: list, add, add-file, remove, clear, test, test-all, help')
    parser.add_argument('arg', nargs='?', help='命令参数')
    
    args = parser.parse_args()
    
    command = args.command or 'help'
    
    if command == 'list':
        list_proxies()
    elif command == 'add':
        if not args.arg:
            print("错误: 请提供代理地址")
            print("示例: python dev/代理配置助手.py add 112.15.190.108:10086")
            return
        add_proxy(args.arg)
    elif command == 'add-file':
        if not args.arg:
            print("错误: 请提供文件路径")
            print("示例: python dev/代理配置助手.py add-file dev/可用代理列表.txt")
            return
        add_proxies_from_file(args.arg)
    elif command == 'remove':
        if not args.arg:
            print("错误: 请提供代理地址")
            print("示例: python dev/代理配置助手.py remove 112.15.190.108:10086")
            return
        remove_proxy(args.arg)
    elif command == 'clear':
        clear_proxies()
    elif command == 'test':
        if not args.arg:
            print("错误: 请提供代理地址")
            print("示例: python dev/代理配置助手.py test 112.15.190.108:10086")
            return
        test_proxy(args.arg)
    elif command == 'test-all':
        test_all_proxies()
    elif command == 'help':
        show_help()
    else:
        print(f"未知命令: {command}")
        show_help()


if __name__ == "__main__":
    # 禁用SSL警告
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    
    main()

